<?php
class SESSION{
    private $lifetime = 10;//时间单位为秒
    private $sessionval = array();//session值
    private $cookieval = '';//cookie存储的对接字符串
    private $filedir = '';//session存储文件夹
    private $filepath = '';//session存储路径
    private $gcrate = 1000;//除以1000即为回收机制启动概率(概率为1即为百分百启动)
    public function __construct(&$p = ''){
        //$_SESSION = isset($_SESSION)?$_SESSION:''; 
        $this->cookieInit();
        $this->sessionInit();
        $this->gc();
    }
    //获取/设置session方法
    public function val($key = '',$val = ''){
        if(empty($key))  return;
        if($val === ''){
            return isset($this->sessionval[$key])?$this->sessionval[$key]:'';
        }else{
            if(empty($val)) return;
            $this->setSession($key,$val);
        }
    }
    //cookie初始化
    protected function cookieInit(){
        if(empty($_COOKIE['PHP_SESSID'])){ //key加了下划线，为了防止与自带session冲突
            $this->cookieval = md5(microtime().rand(0,100000));
        }else{
            $this->cookieval = $_COOKIE['PHP_SESSID'];
        }
        setcookie('PHP_SESSID',$this->cookieval,time()+$this->lifetime);
    }
    //session系统初始化
    protected function sessionInit(){
        if(!empty($this->sessionval)) return;
        $filename = 'session'.$this->cookieval.'.txt';
        $this->filedir = rtrim(str_replace('\\','/',__DIR__),'/').'/sessionfile';
        if(!is_dir($this->filedir)) mkdir($this->filedir);
        $this->filepath = $this->filedir.'/'.$filename;
        if(!file_exists($this->filepath) || time() - filemtime($this->filepath) > $this->lifetime){
            $json = '';
            $content = '';
        }else{
            $json = file_get_contents($this->filepath);
            $content = $json?json_decode($json,1):'';
        }
        $this->sessionval = is_array($content)?$content:array();
        file_put_contents($this->filepath,$json);
    }
    //设置session值
    protected function setSession($key,$val){
        $this->sessionval[$key] = $val;
        file_put_contents($this->filepath,json_encode($this->sessionval,JSON_UNESCAPED_UNICODE));
    }
    //session文件垃圾回收
    protected function gc(){
        $rand = rand(0,1000);
        if($rand < $this->gcrate){
            foreach (scandir($this->filedir) as $value) {
                if($value != '.' && $value != '..'){
                    $path = $this->filedir.'/'.$value;
                    if(time() - filemtime($path) > $this->lifetime){
                        //echo $path;
                        unlink($path);
                    }
                }
            }
        }
    }
}